package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanMediaService;
import com.xuecheng.content.service.TeachplanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 课程计划 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {
    @Autowired
    TeachplanMapper teachplanMapper;
    @Autowired
    TeachplanMediaMapper teachplanMediaMapper;
    @Override
    public List<TeachplanDto> findTeachplanTree(long courseId) {
        return teachplanMapper.selectTreeNodes(courseId);
    }

    /**
     * 新增课程计划
     * @param teachplanDto  课程计划信息
     */
    @Transactional
    @Override
    public void saveTeachplan(SaveTeachplanDto teachplanDto) {

        //课程计划id
        Long id = teachplanDto.getId();
        //修改课程计划
        if(id!=null){
            Teachplan teachplan = teachplanMapper.selectById(id);
            BeanUtils.copyProperties(teachplanDto,teachplan);
            teachplanMapper.updateById(teachplan);
        }else{
            //取出同父同级别的课程计划数量
            int count = getTeachplanCount(teachplanDto.getCourseId(), teachplanDto.getParentid());
            Teachplan teachplanNew = new Teachplan();
            //设置排序号
            teachplanNew.setOrderby(count+1);
            BeanUtils.copyProperties(teachplanDto,teachplanNew);

            teachplanMapper.insert(teachplanNew);
        }

    }

    @Override
    public void deleteTeachplan(Long courseId) {
        Teachplan teachplan = teachplanMapper.selectById(courseId);
        if (teachplan.getParentid() != 0){
            String mediaType = teachplan.getMediaType();
            if (mediaType == null){
                teachplanMapper.deleteById(teachplan);
            }else {
                teachplanMediaMapper.deleteById(courseId);
                teachplanMapper.deleteById(teachplan);
            }
        }else {
            Long aLong = teachplanMapper.selectBigFest(courseId);
            if (aLong == 0){
                teachplanMapper.deleteById(teachplan);
            }else {
                XueChengPlusException.cast("课程计划信息还有子级信息，无法操作", 120409);
            }
        }
    }

    @Override
    public void moveDown(Long id) {
        //课程计划向下移动
        //根据courseId查询课程计划，然后通过parentId判断是小章节还是大章节
        Teachplan teachplan = teachplanMapper.selectById(id);
        if (teachplan.getParentid() != 0) {
            Integer orderby = teachplan.getOrderby();
            //证明是小章节
            //根据父章节的id，找出大章节下面所有小节点
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getParentid,teachplan.getParentid()).eq(Teachplan::getGrade,2);
            List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
            int i = 0;
            for (Teachplan t:
                    teachplans) {
                //找到当前章节的排序字段加一,以此获得下一个章节
                if(t.getOrderby()==orderby+1){
                    i++;
                }
                if(i==1){
                    //进行交换
                    teachplan.setOrderby(t.getOrderby());
                    t.setOrderby(orderby);
                    teachplanMapper.updateById(t);
                    teachplanMapper.updateById(teachplan);
                    break;
                }
            }
            if(i==0){
                XueChengPlusException.cast("当前计划已经在末尾，无法交换");
            }

        } else {
            Integer orderby = teachplan.getOrderby();
            //证明是大章节
            //根据课程的id，找到下一个大章节
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getCourseId,teachplan.getCourseId()).eq(Teachplan::getGrade,1);
            List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
            int i = 0;
            for (Teachplan t:
                    teachplans) {
                //找到当前章节的排序字段加一,以此获得下一个章节
                if(t.getOrderby()==orderby+1){
                    i++;
                }
                if(i==1){
                    //进行交换
                    teachplan.setOrderby(t.getOrderby());
                    t.setOrderby(orderby);
                    teachplanMapper.updateById(t);
                    teachplanMapper.updateById(teachplan);
                    break;
                }
            }
            if(i==0){
                XueChengPlusException.cast("当前计划已经在末尾，无法交换");
            }
        }
    }


    @Override
    public void moveUp(Long id) {
//课程计划向上移动
        //根据courseId查询课程计划，然后通过parentId判断是小章节还是大章节
        Teachplan teachplan = teachplanMapper.selectById(id);
        if (teachplan.getParentid() != 0) {
            Integer orderby = teachplan.getOrderby();
            //证明是小章节
            //根据父章节的id，找出大章节下面所有小节点
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getParentid,teachplan.getParentid()).eq(Teachplan::getGrade,2);
            List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
            int i = 0;
            for (Teachplan t:
                    teachplans) {
                //找到当前章节的排序字段减一,以此获得上一个章节
                if(t.getOrderby()==orderby-1&&(orderby-1)!=0){
                    i++;
                }
                if(i==1){
                    //进行交换
                    teachplan.setOrderby(t.getOrderby());
                    t.setOrderby(orderby);
                    teachplanMapper.updateById(t);
                    teachplanMapper.updateById(teachplan);
                    break;
                }
            }
            if(i==0){
                XueChengPlusException.cast("当前计划已经在顶部，无法交换");
            }

        } else {
            Integer orderby = teachplan.getOrderby();
            //证明是大章节
            //根据课程的id，找到上一个大章节
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getCourseId,teachplan.getCourseId()).eq(Teachplan::getGrade,1);
            List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
            int i = 0;
            for (Teachplan t:
                    teachplans) {
                //找到当前章节的排序字段减一,以此获得上一个章节
                if(t.getOrderby()==orderby-1&&(orderby-1)!=0){
                    i++;
                }
                if(i==1){
                    //进行交换
                    teachplan.setOrderby(t.getOrderby());
                    t.setOrderby(orderby);
                    teachplanMapper.updateById(t);
                    teachplanMapper.updateById(teachplan);
                    break;
                }
            }
            if(i==0){
                XueChengPlusException.cast("当前计划已经在顶部，无法交换");
            }
        }
    }
    /**
     * @description 教学计划绑定媒资
     * @param bindTeachplanMediaDto
     * @return com.xuecheng.content.model.po.TeachplanMedia
     * @author Mr.M
     * @date 2022/9/14 22:20
     */
    @Override
    public TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        //教学计划id
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if (teachplan == null){
            XueChengPlusException.cast("课程计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if (grade != 2){
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }
        //课程id
        Long courseId = teachplan.getCourseId();
        //先删除原来该教学计划绑定的媒资
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId,teachplanId));
        //再添加教学计划与媒资的绑定关系
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        teachplanMedia.setCourseId(courseId);
        teachplanMedia.setTeachplanId(teachplanId);
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setMediaId(bindTeachplanMediaDto.getMediaId());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMediaMapper.insert(teachplanMedia);
        return teachplanMedia;
    }

    @Override
    public void deleteassociationMedia(int teachPlanId, int mediaId) {
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId,teachPlanId)
                .eq(TeachplanMedia::getMediaId,mediaId));
    }


    /**
     * @description 获取最新的排序号
     * @param courseId  课程id
     * @param parentId  父课程计划id
     * @return int 最新排序号
     * @author Mr.M
     * @date 2022/9/9 13:43
     */
    private int getTeachplanCount(long courseId,long parentId){
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,courseId);
        queryWrapper.eq(Teachplan::getParentid,parentId);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        return count;
    }
}
